import functools
import warnings
from datetime import datetime
from sqlalchemy.exc import IntegrityError
from api_test.common_exception.exceptions import FileIsNoneException, ParamsMissedException, \
    ParamsTypeErrorException, NoPerMissionException, FileNotFoundException, ObjectNotFoundException, \
    ObjectIsDeletedException, ParamsIsNullException
from api_test.common.api_response import JsonResponse


def catch_exception(func):
    @functools.wraps(func)
    def wrapper(*args):
        try:
            result = func(*args)
            return result
        except FileIsNoneException as e:
            return JsonResponse(code='999998', msg=e.__str__())
        except (ParamsTypeErrorException, ParamsMissedException, ParamsIsNullException) as e:
            return JsonResponse(code='999996', msg=e.__str__())
        except NoPerMissionException as e:
            return JsonResponse(code="999983", msg=e.__str__())
        except (FileNotFoundException, ObjectNotFoundException, ObjectIsDeletedException) as e:
            return JsonResponse(code="999995", msg=e.__str__())
        except Exception as e:
            if e.__str__() == 'LoadFile matching query does not exist.':
                return JsonResponse(code='999998', msg='未找到符合条件的文件,请检查!')
            import traceback
            print(traceback.format_exc())
            return JsonResponse(code='999995', msg=e.__str__())
    return wrapper


def close_db_connection(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        args[0].session.close()
        return result
    return wrapper


def update_db_operation(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        session = args[0].session
        try:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                func(*args, **kwargs)
                session.commit()
                session.close()
        except IntegrityError:
            import traceback
            print(traceback.format_exc())
            session.rollback()
            session.close()
    return wrapper


def cost_time(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = datetime.now()
        result = func(*args, **kwargs)
        end = datetime.now()
        print(func.__name__ + f'方法执行消耗时间{end-start}')
        return result
    return wrapper
